package com.example.app.ui.health.User;
import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app.R;
import com.example.app.ui.health.User.BleTooth.BlueToothController;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 心率监测活动
 * 负责连接蓝牙设备，接收并处理生物信号数据
 */
public class HeartRateActivity extends AppCompatActivity {
    private static final String TAG = "HeartRateActivity";
    
    // 界面元素
    private TextView tvHeartRate, tvBloodOxygen, tvStatus, tvTemperature, tvPressure;
    private Button btnStartStop, btnDisconnect;
    private HeartRateChartView heartRateChart;
    
    // 蓝牙相关
    private BluetoothSocket bluetoothSocket;
    private OutputStream outputStream;
    private boolean isConnected = false;
    private String deviceAddress;
    private BlueToothController btController;
    
    // 数据处理相关
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    // 心率检测参数
    private static final int FILTER_WINDOW = 5;             // 滤波窗口大小
    private static final int PEAK_DETECTION_WINDOW = 15;    // 峰值检测窗口大小
    private static final int HEART_RATE_BUFFER_SIZE = 10;   // 心率缓冲区大小
    private static final int PEAK_MIN_INTERVAL_MS = 200;    // 峰值最小间隔(ms)，对应300BPM
    private static final double THRESHOLD_RATIO = 0.6;      // 阈值比例
    private static final int FINGER_THRESHOLD = 50000;      // 手指接触阈值
    private static final int LOW_SIGNAL_COUNT = 5;          // 低信号计数器阈值
    
    // 血氧计算参数
    private static final int SPO2_BUFFER_SIZE = 25;         // 血氧计算缓冲区大小
    private static final int SPO2_MIN_VALID = 70;           // 最小有效血氧值
    private static final int SPO2_MAX_VALID = 100;          // 最大有效血氧值
    
    // 数据缓冲区
    private final Deque<Integer> irFilterBuffer = new ArrayDeque<>(FILTER_WINDOW);
    private final Deque<Integer> peakDetectionBuffer = new ArrayDeque<>(PEAK_DETECTION_WINDOW);
    private final Deque<Long> heartbeatTimes = new ArrayDeque<>(HEART_RATE_BUFFER_SIZE);
    private final List<Integer> redBuffer = new ArrayList<>(SPO2_BUFFER_SIZE);
    private final List<Integer> irBuffer = new ArrayList<>(SPO2_BUFFER_SIZE);
    
    // 新增滤波器参数
    private static final double[] BUTTERWORTH_B = {0.0338, 0.0676, 0.0338};  // 巴特沃斯滤波器系数B
    private static final double[] BUTTERWORTH_A = {1.0, -1.4477, 0.5529};    // 巴特沃斯滤波器系数A
    private final double[] irFilterStates = {0, 0};  // 滤波器状态变量
    
    // 新增波谷检测
    private boolean lookingForValley = false;
    private int lastPeakValue = 0;
    private int valleyThreshold = 0;
    
    // 状态变量
    private long lastPeakTime = 0;
    private int lowSignalCounter = 0;
    private float spO2 = 0;
    private boolean measurementActive = false;
    
    // 新增变量
    private int currentHeartRate = 0;
    private int stableCounter = 0;
    private final Deque<Integer> bpmHistory = new ArrayDeque<>(5);  // 存储最近5个心率值
    
    // 调试用开关
    private static final boolean DEBUG_LOGS = true;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_heart_rate);
        
        // 初始化视图
        initViews();
        
        // 获取设备地址并初始化蓝牙控制器
        deviceAddress = getIntent().getStringExtra("DEVICE_ADDRESS");
        btController = new BlueToothController();
        
        // 连接设备
        connectToDevice();
        
        // 设置按钮监听器
        setupButtonListeners();
        
        // 打印初始状态
        if (DEBUG_LOGS) {
            Log.d(TAG, "HeartRateActivity初始化完成，等待连接蓝牙设备: " + deviceAddress);
        }
    }
    
    /**
     * 初始化界面元素
     */
    private void initViews() {
        tvHeartRate = findViewById(R.id.tv_heart_rate);
        tvBloodOxygen = findViewById(R.id.tv_blood_oxygen);
        tvStatus = findViewById(R.id.tv_status);
        tvTemperature = findViewById(R.id.tv_temperature);
        tvPressure = findViewById(R.id.tv_pressure);
        btnStartStop = findViewById(R.id.btn_start_stop);
        btnDisconnect = findViewById(R.id.btn_disconnect);
        heartRateChart = findViewById(R.id.heart_rate_chart);
        
        // 初始禁用开始按钮，等待连接成功后启用
        btnStartStop.setEnabled(false);
    }
    
    /**
     * 设置按钮点击监听器
     */
    private void setupButtonListeners() {
        btnStartStop.setOnClickListener(v -> toggleDataStream());
        btnDisconnect.setOnClickListener(v -> disconnect());
    }
    
    /**
     * 连接到蓝牙设备
     */
    private void connectToDevice() {
        updateStatusUI("正在连接...", Color.YELLOW);
        new ConnectThread().start();
    }

    /**
     * 连接线程
     */
    private class ConnectThread extends Thread {
        @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
        @Override
        public void run() {
            try {
                BluetoothDevice device = btController.find_device(deviceAddress);
                if (device == null) {
                    throw new IOException("设备未找到");
                }
                
                Method method = device.getClass().getMethod("createRfcommSocket", int.class);
                bluetoothSocket = (BluetoothSocket) method.invoke(device, 1);
                
                if (bluetoothSocket == null) {
                    throw new IOException("无法创建蓝牙套接字");
                }
                
                bluetoothSocket.connect();
                outputStream = bluetoothSocket.getOutputStream();
                isConnected = true;
                
                mainHandler.post(() -> {
                    updateStatusUI("已连接", Color.GREEN);
                    btnStartStop.setEnabled(true);
                });
                
                // 启动数据读取线程
                new ReadThread().start();
                
            } catch (Exception e) {
                Log.e(TAG, "连接失败", e);
                mainHandler.post(() -> {
                    updateStatusUI("连接失败: " + e.getMessage(), Color.RED);
                    // 如果连接失败，尝试关闭socket
                    disconnect();
                });
            }
        }
    }
    
    /**
     * 更新状态UI文本和颜色
     */
    private void updateStatusUI(String text, int color) {
        tvStatus.setText(text);
        tvStatus.setTextColor(color);
    }

    /**
     * 数据读取线程
     */
    private class ReadThread extends Thread {
        private static final int BUFFER_SIZE = 1024;
        private final byte[] buffer = new byte[BUFFER_SIZE];
        private final StringBuilder rawData = new StringBuilder();

        @Override
        public void run() {
            InputStream inputStream;
            try {
                inputStream = bluetoothSocket.getInputStream();
            } catch (IOException e) {
                Log.e(TAG, "获取输入流失败", e);
                disconnect();
                return;
            }

            while (isConnected) {
                try {
                    int bytesAvailable = inputStream.available();
                    if (bytesAvailable > 0) {
                        int bytesRead = inputStream.read(buffer, 0, Math.min(bytesAvailable, BUFFER_SIZE));
                        String chunk = new String(buffer, 0, bytesRead);
                        rawData.append(chunk);
                        
                        // 处理完整数据包
                        processDataPackets();
                    } else {
                        // 避免过度消耗CPU
                        Thread.sleep(10);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "读取数据失败", e);
                    disconnect();
                    break;
                }
            }
        }
        
        /**
         * 处理从缓冲区中的完整数据包
         */
        private void processDataPackets() {
            int endIndex;
            // 处理所有完整的行
            while ((endIndex = rawData.indexOf("\n")) != -1) {
                String packet = rawData.substring(0, endIndex).trim();
                rawData.delete(0, endIndex + 1);
                
                if (packet.isEmpty()) continue;
                
                if (measurementActive) {
                    // 在工作线程中处理数据包
                    executor.execute(() -> processPacket(packet));
                }
            }
        }
    }

    /**
     * 处理单个数据包
     */
    private void processPacket(String packet) {
        try {
            // 解析数据包为键值对
            Map<String, String> sensorData = parsePacket(packet);
            
            // 处理各类传感器数据
            if (sensorData.containsKey("IR") && sensorData.containsKey("RED")) {
                int ir = Integer.parseInt(sensorData.get("IR"));
                int red = Integer.parseInt(sensorData.get("RED"));
                
                // 检查信号质量
                checkSignalQuality(ir);
                
                // 如果信号质量足够好，则处理数据
                if (lowSignalCounter < LOW_SIGNAL_COUNT) {
                    processHealthData(ir, red);
                }
            }
            
            // 处理温度数据
            if (sensorData.containsKey("BMP_TEMP")) {
                float temperature = Float.parseFloat(sensorData.get("BMP_TEMP"));
                updateTemperatureUI(temperature);
            }
            
            // 处理气压数据
            if (sensorData.containsKey("PRESSURE")) {
                float pressure = Float.parseFloat(sensorData.get("PRESSURE"));
                updatePressureUI(pressure);
            }
        } catch (Exception e) {
            Log.e(TAG, "处理数据包失败: " + packet, e);
        }
    }
    
    /**
     * 解析数据包字符串为Map
     */
    private Map<String, String> parsePacket(String packet) {
        Map<String, String> data = new HashMap<>();
        String[] pairs = packet.split(",");
        
        for (String pair : pairs) {
            String[] keyValue = pair.split("=");
            if (keyValue.length == 2) {
                data.put(keyValue[0].trim(), keyValue[1].trim());
            }
        }
        
        return data;
    }
    
    /**
     * 检查信号质量
     */
    private void checkSignalQuality(int irValue) {
        if (irValue < FINGER_THRESHOLD) {
            lowSignalCounter++;
            if (lowSignalCounter == LOW_SIGNAL_COUNT) {
                // 信号质量不足，更新UI
                mainHandler.post(() -> {
                    tvHeartRate.setText("--");
                    tvBloodOxygen.setText("--%");
                    updateStatusUI("请将手指放在传感器上", Color.RED);
                });
            }
        } else {
            // 信号质量良好
            if (lowSignalCounter >= LOW_SIGNAL_COUNT) {
                mainHandler.post(() -> updateStatusUI("测量中", Color.GREEN));
            }
            lowSignalCounter = Math.max(0, lowSignalCounter - 1);
        }
    }
    
    /**
     * 处理健康数据(心率和血氧)
     */
    private void processHealthData(int ir, int red) {
        // 应用巴特沃斯滤波器
        int filteredIr = applyButterworthFilter(ir);
        
        // 存储数据到缓冲区(用于血氧计算)
        addToBuffers(red, ir);
        
        // 检测心跳并计算心率
        detectHeartbeat(filteredIr);
        
        // 计算血氧饱和度
        calculateSpO2();
    }
    
    /**
     * 应用巴特沃斯低通滤波器（更高级的滤波器，减少噪声）
     */
    private int applyButterworthFilter(int newValue) {
        // 更高级的巴特沃斯滤波器实现
        double filtered = BUTTERWORTH_B[0] * newValue + irFilterStates[0];
        irFilterStates[0] = BUTTERWORTH_B[1] * newValue - BUTTERWORTH_A[1] * filtered + irFilterStates[1];
        irFilterStates[1] = BUTTERWORTH_B[2] * newValue - BUTTERWORTH_A[2] * filtered;
        
        // 添加到移动平均滤波缓冲区以进一步平滑
        int roundedValue = (int) Math.round(filtered);
        irFilterBuffer.add(roundedValue);
        if (irFilterBuffer.size() > FILTER_WINDOW) {
            irFilterBuffer.removeFirst();
        }
        
        // 计算移动平均值
        int sum = 0;
        for (int val : irFilterBuffer) {
            sum += val;
        }
        return sum / irFilterBuffer.size();
    }
    
    /**
     * 将数据添加到缓冲区
     */
    private void addToBuffers(int red, int ir) {
        // 添加到血氧计算缓冲区
        redBuffer.add(red);
        irBuffer.add(ir);
        
        // 维持缓冲区大小
        if (redBuffer.size() > SPO2_BUFFER_SIZE) {
            redBuffer.remove(0);
        }
        if (irBuffer.size() > SPO2_BUFFER_SIZE) {
            irBuffer.remove(0);
        }
    }
    
    /**
     * 检测心跳并计算心率
     * 使用峰值和波谷检测算法，类似于医疗设备的方法
     */
    private void detectHeartbeat(int filteredIr) {
        // 添加到峰值检测缓冲区
        peakDetectionBuffer.add(filteredIr);
        if (peakDetectionBuffer.size() > PEAK_DETECTION_WINDOW) {
            peakDetectionBuffer.removeFirst();
        }
        
        // 至少需要完整的窗口才能检测
        if (peakDetectionBuffer.size() < PEAK_DETECTION_WINDOW) {
            return;
        }
        
        // 获取中间值(当前值)
        Integer[] values = peakDetectionBuffer.toArray(new Integer[0]);
        int midIndex = PEAK_DETECTION_WINDOW / 2;
        int currentValue = values[midIndex];
        
        // 获取窗口的最大值和最小值
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        
        for (int value : values) {
            if (value > max) max = value;
            if (value < min) min = value;
        }
        
        // 动态阈值计算，自适应到信号幅度
        double threshold = min + (max - min) * THRESHOLD_RATIO;
        
        // 调试信号特征
        Log.d(TAG, "信号值: " + currentValue + ", 窗口最大值: " + max + ", 窗口最小值: " + min + ", 阈值: " + threshold);
        
        // 峰值-波谷检测模式
        long currentTime = System.currentTimeMillis();
        
        if (!lookingForValley) {
            // 寻找峰值模式
            boolean isPeak = currentValue > threshold;
            
            // 确认是局部最大值
            for (int i = 0; i < values.length; i++) {
                if (i != midIndex && values[i] >= currentValue) {
                    isPeak = false;
                    break;
                }
            }
            
            if (isPeak) {
                Log.d(TAG, "检测到峰值: " + currentValue + ", 当前时间: " + currentTime + ", 上一峰值时间: " + lastPeakTime);
                
                // 检查是否是有效的心跳(不能太近)
                if (lastPeakTime > 0 && currentTime - lastPeakTime > PEAK_MIN_INTERVAL_MS) {
                    lastPeakValue = currentValue;
                    valleyThreshold = (int)(min + (currentValue - min) * 0.3); // 设定波谷阈值
                    lookingForValley = true; // 开始寻找波谷
                    Log.d(TAG, "切换到波谷检测模式, 波谷阈值: " + valleyThreshold);
                }
                
                lastPeakTime = currentTime;
            }
        } else {
            // 寻找波谷模式
            boolean isValley = currentValue < valleyThreshold;
            
            // 确认是局部最小值
            for (int i = 0; i < values.length; i++) {
                if (i != midIndex && values[i] <= currentValue) {
                    isValley = false;
                    break;
                }
            }
            
            if (isValley) {
                Log.d(TAG, "检测到波谷: " + currentValue + ", 波谷阈值: " + valleyThreshold);
                
                // 找到波谷，说明一个完整心动周期完成
                // 记录心跳间隔
                long interval = currentTime - lastPeakTime;
                Log.d(TAG, "心跳间隔: " + interval + "ms");
                
                // 添加到心跳时间缓冲区
                heartbeatTimes.add(interval);
                if (heartbeatTimes.size() > HEART_RATE_BUFFER_SIZE) {
                    heartbeatTimes.removeFirst();
                }
                
                // 计算心率
                if (heartbeatTimes.size() >= 3) { // 至少需要3次心跳才能计算
                    calculateHeartRate();
                }
                
                lookingForValley = false; // 切换回寻找峰值模式
                Log.d(TAG, "切换到峰值检测模式");
            }
        }
    }
    
    /**
     * 计算心率，使用中值滤波器平滑结果
     */
    private void calculateHeartRate() {
        // 移除异常值
        List<Long> validIntervals = new ArrayList<>();
        long sumValid = 0;
        
        for (long interval : heartbeatTimes) {
            // 60-240 BPM 对应的间隔范围
            if (interval >= 250 && interval <= 1000) {
                validIntervals.add(interval);
                sumValid += interval;
            }
        }
        
        if (validIntervals.size() >= 3) { // 确保有足够的数据
            // 计算中位数（比平均值更能抵抗异常值）
            validIntervals.sort(null);
            long medianInterval = validIntervals.get(validIntervals.size() / 2);
            
            // 计算BPM
            int bpm = (int) (60000 / medianInterval);
            
            // 调试心跳间隔和对应的BPM
            Log.d(TAG, "心跳间隔(ms): " + medianInterval + ", 计算的BPM: " + bpm);
            
            // 心率平滑处理
            bpmHistory.add(bpm);
            if (bpmHistory.size() > 5) {
                bpmHistory.removeFirst();
            }
            
            // 计算平滑心率（舍弃最大值和最小值后的平均值）
            if (bpmHistory.size() >= 3) {
                List<Integer> sortedBpm = new ArrayList<>(bpmHistory);
                sortedBpm.sort(null);
                
                // 调试bpmHistory内容
                Log.d(TAG, "BPM历史: " + bpmHistory);
                
                // 移除最大和最小值
                if (sortedBpm.size() > 3) {
                    sortedBpm.remove(0);
                    sortedBpm.remove(sortedBpm.size() - 1);
                }
                
                // 计算平均值
                int sum = 0;
                for (int rate : sortedBpm) {
                    sum += rate;
                }
                int averageBpm = sum / sortedBpm.size();
                
                // 调试平滑后的BPM
                Log.d(TAG, "平滑后的BPM: " + averageBpm + ", 稳定计数: " + stableCounter);
                
                // 心率有效性检查
                if (averageBpm >= 40 && averageBpm <= 200) {
                    // 心率稳定检查
                    if (Math.abs(averageBpm - currentHeartRate) <= 3) {
                        stableCounter++;
                    } else {
                        stableCounter = 0;
                    }
                    
                    currentHeartRate = averageBpm;
                    
                    // 稳定几次后才更新UI，防止抖动
                    if (stableCounter >= 2) {
                        updateHeartRateUI(currentHeartRate);
                    }
                }
            }
        }
    }
    
    /**
     * 计算血氧饱和度 - 优化算法
     */
    private void calculateSpO2() {
        // 需要足够的数据
        if (redBuffer.size() < SPO2_BUFFER_SIZE || irBuffer.size() < SPO2_BUFFER_SIZE) {
            return;
        }
        
        // 计算红光和红外光的DC分量(平均值)
        float redDC = calculateMean(redBuffer);
        float irDC = calculateMean(irBuffer);
        
        // 计算AC分量(标准差)
        float redAC = calculateStd(redBuffer, redDC);
        float irAC = calculateStd(irBuffer, irDC);
        
        // 质量检查 - AC分量必须达到一定大小才有效
        if (redAC < 50 || irAC < 50) {
            return;
        }
        
        // 计算R比值（血氧饱和度的关键指标）
        float ratio = (redAC / redDC) / (irAC / irDC);
        
        // 优化的经验公式计算SpO2，根据医疗设备校准
        float newSpO2 = -45.060f * ratio * ratio + 30.354f * ratio + 94.845f;
        
        // 应用指数平滑，减少抖动
        spO2 = 0.15f * newSpO2 + 0.85f * spO2;
        
        // 限制在有效范围内
        spO2 = Math.max(SPO2_MIN_VALID, Math.min(SPO2_MAX_VALID, spO2));
        
        // 更新UI
        updateSpO2UI();
    }
    
    /**
     * 计算列表的平均值
     */
    private float calculateMean(List<Integer> values) {
        float sum = 0;
        for (int value : values) {
            sum += value;
        }
        return sum / values.size();
    }
    
    /**
     * 计算列表的标准差
     */
    private float calculateStd(List<Integer> values, float mean) {
        float sumSquares = 0;
        for (int value : values) {
            float diff = value - mean;
            sumSquares += diff * diff;
        }
        return (float) Math.sqrt(sumSquares / values.size());
    }
    
    /**
     * 更新心率UI
     */
    private void updateHeartRateUI(int bpm) {
        if (DEBUG_LOGS) {
            Log.d(TAG, "更新心率UI，值: " + bpm);
        }
        
        mainHandler.post(() -> {
            // 更新文本显示
            tvHeartRate.setText(String.valueOf(bpm));
            
            try {
                // 更新图表 - 确保在主线程中调用
                heartRateChart.addHeartRate(bpm);
                
                // 强制立即重绘图表
                heartRateChart.invalidate();
                
                Log.d(TAG, "成功更新心率UI和图表，值: " + bpm);
            } catch (Exception e) {
                Log.e(TAG, "更新心率图表时出错: " + e.getMessage(), e);
            }
        });
    }
    
    /**
     * 更新血氧UI
     */
    private void updateSpO2UI() {
        int roundedSpO2 = Math.round(spO2);
        
        if (DEBUG_LOGS) {
            Log.d(TAG, "更新血氧UI，值: " + roundedSpO2);
        }
        
        mainHandler.post(() -> {
            // 更新文本显示
            tvBloodOxygen.setText(roundedSpO2 + "%");
            
            try {
                // 更新图表 - 确保在主线程中调用
                heartRateChart.addSpO2(spO2);
                
                // 强制立即重绘图表
                heartRateChart.invalidate();
                
                Log.d(TAG, "成功更新血氧UI和图表，值: " + roundedSpO2);
            } catch (Exception e) {
                Log.e(TAG, "更新血氧图表时出错: " + e.getMessage(), e);
            }
        });
    }
    
    /**
     * 更新温度UI
     */
    private void updateTemperatureUI(float temperature) {
        mainHandler.post(() -> {
            tvTemperature.setText(String.format("%.1f°C", temperature));
        });
    }
    
    /**
     * 更新压力UI
     */
    private void updatePressureUI(float pressure) {
        mainHandler.post(() -> {
            tvPressure.setText(String.format("%.1fhPa", pressure));
        });
    }
    
    /**
     * 切换数据流(开始/停止测量)
     */
    private void toggleDataStream() {
        if (!isConnected) return;
        
        measurementActive = !measurementActive;
        String command = measurementActive ? "START" : "STOP";
        
        // 发送命令
        sendCommand(command);
        
        // 更新按钮文本
        btnStartStop.setText(measurementActive ? "停止" : "开始");
        
        if (!measurementActive) {
            // 停止测量时清除图表
            heartRateChart.clearData();
            Log.d(TAG, "已停止测量，清除图表数据");
        } else {
            // 开始测量时重置状态变量
            resetStateVariables();
            Log.d(TAG, "开始测量，已重置状态变量");
            
            // 安排一个延迟任务，定期检查图表状态
            mainHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (measurementActive) {
                        heartRateChart.debugStatus();
                        heartRateChart.refreshChart();
                        // 继续安排下一次检查
                        mainHandler.postDelayed(this, 5000); // 5秒后再次检查
                    }
                }
            }, 5000); // 5秒后首次检查
        }
    }
    
    /**
     * 发送命令到设备
     */
    private void sendCommand(String command) {
        try {
            if (outputStream != null) {
                outputStream.write((command + "\n").getBytes());
                Log.d(TAG, "命令已发送: " + command);
            }
        } catch (IOException e) {
            Log.e(TAG, "发送命令失败", e);
            Toast.makeText(this, "发送命令失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 断开连接
     */
    private void disconnect() {
        // 停止数据收集
        if (measurementActive) {
            toggleDataStream();
        }
        
        isConnected = false;
        
        // 关闭蓝牙连接
        if (bluetoothSocket != null) {
            try {
                bluetoothSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "关闭蓝牙套接字失败", e);
            } finally {
                bluetoothSocket = null;
            }
        }
        
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        disconnect();
        executor.shutdown();
    }
    
    /**
     * 重置所有状态变量
     */
    private void resetStateVariables() {
        irFilterBuffer.clear();
        peakDetectionBuffer.clear();
        heartbeatTimes.clear();
        redBuffer.clear();
        irBuffer.clear();
        bpmHistory.clear();
        
        irFilterStates[0] = 0;
        irFilterStates[1] = 0;
        
        lastPeakTime = 0;
        lowSignalCounter = 0;
        spO2 = 0;
        lastPeakValue = 0;
        lookingForValley = false;
        currentHeartRate = 0;
        stableCounter = 0;
        
        // 开始测试数据（仅用于调试）
        if (DEBUG_LOGS) {
            startTestDataGeneration();
        }
    }
    
    /**
     * 生成测试数据以验证图表功能正常（仅调试用）
     */
    private void startTestDataGeneration() {
        Log.d(TAG, "开始生成测试数据");
        
        // 创建一个定期任务来添加测试数据
        mainHandler.postDelayed(new Runnable() {
            private int counter = 0;
            private final int MAX_TEST_DATA = 20; // 最多生成20个测试数据点
            
            @Override
            public void run() {
                if (measurementActive && counter < MAX_TEST_DATA) {
                    // 生成模拟数据
                    int testHR = 70 + (int)(Math.random() * 10); // 70-80范围的心率
                    float testSpO2 = 95 + (float)(Math.random() * 3); // 95-98范围的血氧
                    
                    Log.d(TAG, "生成测试数据点 #" + counter + ": HR=" + testHR + ", SpO2=" + testSpO2);
                    
                    // 直接更新UI
                    updateHeartRateUI(testHR);
                    spO2 = testSpO2;
                    updateSpO2UI();
                    
                    counter++;
                    // 安排下一次更新
                    mainHandler.postDelayed(this, 1000); // 每秒添加一个数据点
                } else {
                    Log.d(TAG, "测试数据生成完成或测量已停止");
                }
            }
        }, 2000); // 2秒后开始生成测试数据
    }
}